﻿using AutoMapper;
using PowerHub.MES.Common.NumberingCenter;
using PowerHub.MES.DTO.Crew.DTO;
using PowerHub.MES.DTO.Crew.QueryDto;
using PowerHub.MES.EFBase;
using PowerHub.MES.Entities.Crew;
using PowerHub.MES.Entities;
using PowerHub.MES.IRepository.ICrew;
using PowerHub.MES.IServices.ICrew;
using PowerHub.MES.Jwt;
using PowerHub.MES.ReturnEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PowerHub.MES.DTO.ProductPlanning.DTO;
using PowerHub.MES.Entities.ProductPlanning;
using PowerHub.MES.DTO.ProductPlanning.QueryDTO;
using PowerHub.MES.IServices.IProductPlanning;
using PowerHub.MES.IRepository.IProductPlanning;
using PowerHub.MES.IRepository.IProcessRoute;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using PowerHub.MES.DTO.ProcessRoute.QueryDto;
using Microsoft.AspNetCore.Mvc;

namespace PowerHub.MES.Services.ProductPlanning
{

    /// <summary>
    /// 产品接口实现层
    /// </summary>
    public class ProductPlanning_ProductBillServices : BaseServices<ProductPlanning_ProductBill>, IProductPlanning_ProductBillServices
    {
        private IProductPlanning_ProductBillRepository _iProductPlanning_ProductBillRepository;
        public UserServices _userServices;
        private IMapper _mapper;
        private static Random random = new Random();
        private IProcessRoute_CraftBillDetialRepository _processRoute_CraftBillDetialRepository;
        private IProductPlanning_ProductBillDetialRepository _productPlanning_ProductBillDetialRepository;

        public ProductPlanning_ProductBillServices(PowerHubMesContext powerHubMesContext, IProductPlanning_ProductBillRepository iProductPlanning_ProductBillRepository,
            UserServices userServices, IMapper mapper, IProcessRoute_CraftBillDetialRepository processRoute_CraftBillRepository, IProductPlanning_ProductBillDetialRepository productPlanning_ProductBillDetialRepository) : base(powerHubMesContext)
        {
            _iProductPlanning_ProductBillRepository = iProductPlanning_ProductBillRepository;
            _processRoute_CraftBillDetialRepository = processRoute_CraftBillRepository;
            _userServices = userServices;
            _mapper = mapper;
            this._productPlanning_ProductBillDetialRepository = productPlanning_ProductBillDetialRepository;
        }

        /// <summary>
        /// 获取产品列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationPageResult<List<ProductPlanning_ProductBill>>> GetProductPlanning_ProductBillPageListAsync(QueryProductPlanning_ProductBillDTO query)
        {
            var ss = _userServices.UserId;
            var UserName = _userServices.UserName;
            var Role = _userServices.Role;
            return await _iProductPlanning_ProductBillRepository.GetProductPlanning_ProductBillPageListAsync(query);
        }

        /// <summary>
        /// 添加产品
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> CreateProductPlanning_ProductBillAsync(ProductPlanning_ProductBillDTO query)
        {
            ProductPlanning_ProductBill foundation = await GetEntityAsync(d => d.ProductBillName.Equals(query.ProductBillName) && d.IsDel == 0);
            if (foundation != null)
            {
                throw new Exception("你输入的产品名称已存在！");
            }
            //实体转换
            var ProductPlanning_ProductBill = _mapper.Map<ProductPlanning_ProductBill>(query);
            ProductPlanning_ProductBill.Id = Guid.NewGuid().ToString();
            ProductPlanning_ProductBill.ProductBillNo = string.IsNullOrEmpty(query.ProductBillNo) || query.ProductBillNo.Contains(" ") ? GenerateBasicDataNO.GenerateCode(query.ProductBillName) : query.ProductBillNo;
            ProductPlanning_ProductBill.Creator = _userServices.UserName;

            //设置明细id
            foreach (var item in ProductPlanning_ProductBill.ProductPlanningProductBillDetials)
            {
                item.Id = Guid.NewGuid().ToString();
            }

            return await _iProductPlanning_ProductBillRepository.CreateProductPlanning_ProductBillAsync(ProductPlanning_ProductBill);
        }


        /// <summary>
        /// 批量删除产品
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> DeletionProductPlanning_ProductBillAsync(List<string>? ids)
        {
            if (ids.Count < 1)
            {
                throw new Exception("请先选择数据！");
            }
            return await _iProductPlanning_ProductBillRepository.DeletionProductPlanning_ProductBillAsync(ids);
        }


        /// <summary>
        /// 更新产品
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> UpdateProductPlanning_ProductBillAsync(ProductPlanning_ProductBillDTO query)
        {
            if (query == null)
            {
                throw new Exception("请先选择数据！");
            }

            //根据id获取产品信息
            ProductPlanning_ProductBill ProductPlanning_ProductBill = await GetEntityAsync(d => d.Id.Equals(query.Id));
            if (ProductPlanning_ProductBill == null)
            {
                throw new Exception("更新产品信息发生了异常,请刷新页面后试试");
            }
            query.ProductPlanningProductBillDetials = null;
            //ProductPlanning_ProductBill =  _mapper.Map<ProductPlanning_ProductBill>(query);
            //ProductPlanning_ProductBill.Updator = _userServices.UserName;

            // 在使用 AutoMapper 进行映射时，确保映射的目标对象是从数据库中获取到的实体
            _mapper.Map(query, ProductPlanning_ProductBill);

            // 更新其他属性
            ProductPlanning_ProductBill.Updator = _userServices.UserName;


            return await _iProductPlanning_ProductBillRepository.UpdateProductPlanning_ProductBillAsync(ProductPlanning_ProductBill);

        }


        /// <summary>
        ///根据产品id获取产品
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<ProductPlanning_ProductBillDTOS>> GetProductPlanning_ProductBillByIdListAsync(QueryProductPlanning_ProductBillDTO productBillId)
        {
            var ressult = new OperationResult<ProductPlanning_ProductBillDTOS>();
            var productBill = await _iProductPlanning_ProductBillRepository.GetProductPlanning_ProductBillByIdListAsync(productBillId);

            //实体转换
            var productBillDTOS = _mapper.Map<ProductPlanning_ProductBillDTOS>(productBill);
            productBillDTOS.ProductPlanningProductBillDetials = productBillDTOS.ProductPlanningProductBillDetials.Where(p => p.IsDel == 0).ToList();

            var CraftBillDetial = await _processRoute_CraftBillDetialRepository.GetProcessRoute_CraftBillDetialPageListAsync(new QueryProcessRoute_CraftBillDTO() { CraftBillId = productBillDTOS.CraftBillId });
            productBillDTOS.ProcessRouteCraftBillDetial = CraftBillDetial.Data;

            ressult.Data = productBillDTOS;
            return ressult;
        }

        /// <summary>
        /// 添加产品BOM
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<bool>> CreateProductPlanning_ProductBillDetialAsync(List<ProductPlanning_ProductBillDetialDTO> query)
        {
            //判断产品是否为空
            var emptyProductBillIdItems = query.Where(item => string.IsNullOrEmpty(item.ProductBillId)).ToList();
            if (emptyProductBillIdItems.Count > 0)
            {
                throw new Exception("找不到当前产品信息，你重新打开试试!");
            }

            //判断是否已经存在
            var data = query.FirstOrDefault();
            var ProductBillDetials = await _productPlanning_ProductBillDetialRepository.GetProductPlanning_ProductBillDetialListAsync(query.Select(g => g.MaterialsId).ToList(), data.ProductBillId);
            if (ProductBillDetials.Count > 0)
            {
                throw new Exception("存在重复项,请重新选择!");
            }

            var productBillDetial = _mapper.Map<List<ProductPlanning_ProductBillDetial>>(query);
            productBillDetial.ForEach(w => w.Id = Guid.NewGuid().ToString());

            return await _productPlanning_ProductBillDetialRepository.CreateProductPlanning_ProductBillDetialAsync(productBillDetial);
        }


        /// <summary>
        /// 修改产品BOM清单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<OperationResult<bool>> UpdateProductPlanning_ProductBillDetialAsync(ProductPlanning_ProductBillDetial query)
        {
            return await _productPlanning_ProductBillDetialRepository.UpdateProductPlanning_ProductBillDetialAsync(query);
        }
        /// <summary>
        /// 删除产品BOM清单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<OperationResult<bool>> DeletionProductPlanning_ProductBillDetialAsync(List<string>? query)
        {
            return await _productPlanning_ProductBillDetialRepository.DeletionProductPlanning_ProductBillDetialAsync(query);
        }
    }
}
